import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from "../views/Login";
import store from '../store'

Vue.use(VueRouter)

const routes = [
	{
		path: '/',
		name: 'Home',
		component: Home,
		children: [
			{
				path: '/index',
				name: 'Index',
				component: () => import('@/views/Index.vue')
			}
		]
	},
	{
		path: '/login',
		name: 'Login',
		component: Login
	},
	{
		path: '/about',
		name: 'About',
		component: () => import('../views/About.vue')
	}
]

const menus = [
	{
		name: 'SysManga',
		title: '系统管理',
		icon: 'el-icon-s-operation',
		path: '',
		component: '',
		children: [
			{
				name: 'SysUser',
				title: '用户管理',
				icon: 'el-icon-s-custom',
				path: '/sys/users',
				component: 'sys/User',
				children: []
			}
		]
	},
	{
		name: 'SysTools',
		title: '系统工具',
		icon: 'el-icon-s-tools',
		path: '',
		component: '',
		children: [
			{
				name: 'CodeCreate',
				title: '代码生成',
				icon: 'el-icon-files',
				path: '/tools/1',
				component: 'sys/CodeCreate',
				children: []
			},
			{
				name: 'SysDict',
				title: '数字字典',
				icon: 'el-icon-s-order',
				path: '/tools/2',
				component: 'sys/Dict',
				children: []
			},
		]
	}
]

const router = new VueRouter({
	mode: 'history',
	base: process.env.BASE_URL,
	routes
})


router.beforeEach((to, from, next) => {
	// store.commit("addTabs", to)

	let hasRoute = store.state.menus.hasRoute

	if (!hasRoute) {
		let newRoutes = router.options.routes;
		console.log(newRoutes)

		menus.forEach(menu => {
			if (menu.children) {
				menu.children.forEach(e => {

					let route = menuToRoute(e)
					if(route) {
						newRoutes[0].children.push(route)
					}
				})
			}
		})

		console.log("oldRoutes---------------")
		console.log(newRoutes)

		router.addRoutes(newRoutes)

		store.commit("changeRouteStatus", true)

		next({path: to.path})

	} else {
		console.log("已经有路由了------------")
		next()
	}

})

// 二级菜单才是路由
// const menuChildToRoute = (menu) => {
//
// 	let routes = []
//
// 	if (menu.children) {
// 		menu.children.forEach(e => {
//
// 			let route = menuToRoute(e)
// 			routes.push(route)
// 		})
// 	}
// 	console.log(menu.title + " - routes------------------")
// 	console.log(routes)
// 	console.log("------------------")
//
// 	return routes
// }

const menuToRoute = (menu) => {

	if (!menu.component) {
		return null
	}
	// 复制属性
	let route = {
		name: menu.name,
		path: menu.path,
		meta: {
			icon: menu.icon,
			title: menu.title
		}
	}

	route.component = () => import('@/views/' + menu.component +'.vue')

	console.log("start-----------------------------")
	console.log(menu.title)
	console.log(route)
	console.log("end-----------------------------")

	return route
}


export default router
